#!/bin/bash
set -e
set -u
#
# This systemtest tests the plugin functionality
# of the Susan FD by using the supplied module
#   susan-fd-local-fileset.py
#
# The module will backup some files.
# This plugin is not intended for production,
# but is only a minimal example that shows
# how to use the python plugin interface.
# File attributes like uses and times will not be saved.
#
TestName="$(basename "$(pwd)")"
export TestName
bucket_name=susan-test

JobName=backup-susan-fd
#shellcheck source=../environment.in
. ./environment

JobName=backup-susan-fd
#shellcheck source=../scripts/functions
. "${rscripts}"/functions
"${rscripts}"/cleanup
"${rscripts}"/setup

# shortcut for s3cmd
S3="${S3CMD} --config ${S3CFG}"


# Directory to backup.
# This directory will be created by setup_data "$@"().
BackupDirectory="${tmp}/data"

# Use a tgz to setup data to be backed up.
# Data will be placed at "${tmp}/data/".
setup_data "$@"

"${SYSTEMTESTS_DIR}"/scripts/start_minio.sh "$MINIO_PORT" "$TestName"

# create s3 content for test
${S3} rb --recursive --force s3://$bucket_name || echo "s3://$bucket_name does not exist"
${S3} mb s3://$bucket_name


# this test does not work with links and some other weird files as they would already
# have a changed name by syncing to S3 using s3cmd
find ${tmp}/data/weird-files -type l -exec rm {} \;
find ${tmp}/data/weird-files -links +1 -type f -exec rm {} \;
rm ${tmp}/data/weird-files/fifo*
rm ${tmp}/data/weird-files/newline*
rm ${tmp}/data/weird-files/tab*
# s3cmd does not sync empty dirs
rmdir ${tmp}/data/weird-files/big-X
rmdir ${tmp}/data/weird-files/subdir

${S3} sync "$BackupDirectory" s3://$bucket_name

start_test

cat <<END_OF_DATA >$tmp/bconcmds
@$out /dev/null
messages
@$out $tmp/log1.out
setdebug level=100 storage=File
setdebug level=100 client=susan-fd trace=1 timestamp=1
label volume=TestVolume001 storage=File pool=Full
run job=$JobName yes
status director
status client
status storage=File
wait
messages
@#
@# now do a restore
@#
@$out $tmp/log2.out
wait
restore client=susan-fd fileset=PluginTest where=$tmp/susan-restores select all done
yes
wait
messages
quit
END_OF_DATA

run_susan "$@"
check_for_zombie_jobs storage=File
stop_susan

check_two_logs
list=( $(find "${BackupDirectory}" -type f) )
# Using check_restore_only_files_diff instead of check_restore_diff
# to don'"t diff the file attributes, because they are not saved
#check_restore_only_files_diff "${list[@]}"

if ! diff -r tmp/data tmp/susan-restores/$bucket_name/data; then
  export estat=1
fi

"${SYSTEMTESTS_DIR}"/scripts/stop_minio.sh "$TestName"

end_test
